package com.huaxinkai.mobile.controller;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.huaxinkai.mobile.entity.AccessToken;
import com.huaxinkai.mobile.entity.JsAPITicket;
import com.huaxinkai.mobile.service.IUpdateAccessTokenService;
import com.huaxinkai.mobile.util.wechatUtil.WechatAccessToken;
import com.huaxinkai.mobile.util.wechatUtil.WechatCheck;
import com.huaxinkai.mobile.util.wechatUtil.WechatCoreService;
import com.huaxinkai.mobile.util.wechatUtil.WechatJSTicketUtil;
import com.huaxinkai.mobile.util.wechatUtil.WeixinUtil;
import com.huaxinkai.mobile.util.wechatUtil.bean.menubean.Menu;
import com.huaxinkai.mobile.util.wechatUtil.bean.wxconfig.WxConfig;

import net.sf.json.JSONObject;
/**
 * 处理微信消息
 * @author liuzh
 * @data 2016年12月31日下午3:08:48
 */
@Controller
public class WechatMessage {
	
	@Autowired
	private IUpdateAccessTokenService updateAccessTokenService;
	
	/**
	 * 微信signature验证
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @param response
	 */
	@RequestMapping(value="/wechat.htm",method=RequestMethod.GET)
	public void signature(
			@RequestParam(value="signature") String signature,
			@RequestParam(value="timestamp") String timestamp,
			@RequestParam(value="nonce") String nonce,
			@RequestParam(value="echostr") String echostr,
			HttpServletResponse response 
			){
		try {
			PrintWriter write = response.getWriter();
			if (WechatCheck.checkSignatrue(signature, timestamp, nonce)) {
				write.print(echostr);
				System.out.println("------微信signature验证--成功----");
			}else{
				System.out.println("------微信signature验证--不成功----");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 微信回复消息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/wechat.htm",method=RequestMethod.POST)
	public void message(HttpServletRequest request,HttpServletResponse response){
		PrintWriter write = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			System.out.println("---有微信消息发来了---");
			write = response.getWriter();
			String message = WechatCoreService.processRequest(request);
			System.out.println(message);
			write.write(message);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			write.close();
		}
	}
	
	/**
	 * 微信更新token
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/updateTokenTest.htm")
	public void addTokenTest(HttpServletRequest request,HttpServletResponse response){
		AccessToken at = null;
		String  result = null;
		PrintWriter out = null;
		try {
			at = updateAccessTokenService.queryToken();
			if(at == null){
				at = WechatAccessToken.getAccessToken();
				updateAccessTokenService.addAccessToken(at);
				System.out.println("-------------- 新增 token 成功  --------------- ");
			}else if(at.getLoseEfficacyDate().getTime() < new Date().getTime()){
				AccessToken act = WechatAccessToken.getAccessToken();
				at.setExpiresIn(act.getExpiresIn());
				at.setLoseEfficacyDate(act.getLoseEfficacyDate());
				at.setToken(act.getToken());
				at.setUpdateDate(act.getUpdateDate());
				updateAccessTokenService.updateToken(at);;
				System.out.println("-------------- 更新  token 成功  --------------- ");
				
			}else{
				System.out.println("--------------  token  没有过期  --------------- ");
			}
			out = response.getWriter();
			result = JSONObject.fromObject(at).toString();
			out.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
			if( out != null){
				out.close();
			}
		}
	}
	
	@RequestMapping(value="/updateToken.htm")
	public void addToken(HttpServletResponse response){
		AccessToken at = null;
		String  result = null;
		PrintWriter out = null;
		try {
			at = updateAccessTokenService.queryToken();
			if(at == null){
				at = WechatAccessToken.getAccessToken();
				updateAccessTokenService.addAccessToken(at);
			}else if(at !=null){
				AccessToken act = WechatAccessToken.getAccessToken();
				at.setExpiresIn(act.getExpiresIn());
				at.setLoseEfficacyDate(act.getLoseEfficacyDate());
				at.setToken(act.getToken());
				at.setUpdateDate(act.getUpdateDate());
				updateAccessTokenService.updateToken(at);;
				System.out.println("-------------- 强制更新    token  成功  --------------- ");
			}
			out = response.getWriter();
			result = JSONObject.fromObject(at).toString();
			out.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 更新、获取js ticket
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/updateTicketTest.htm")
	public void updateJSTicketTest(HttpServletRequest request,HttpServletResponse response){
		AccessToken at = null;
		String  result = null;
		PrintWriter out = null;
		JsAPITicket ticket = null;
		try {
			ticket = updateAccessTokenService.queryTicket();
			out = response.getWriter();
			if(ticket == null ){
				at = updateAccessTokenService.queryToken();
				ticket = WechatJSTicketUtil.getJSTicket(at.getToken());
				updateAccessTokenService.addTicket(ticket);
				System.out.println("-------------- 新增  js ticket 成功  --------------- ");
			}else if(ticket.getLoseEfficacyDate().getTime() < new Date().getTime()){
				at = updateAccessTokenService.queryToken();
				JsAPITicket newTicket = WechatJSTicketUtil.getJSTicket(at.getToken());
				ticket.setTicket(newTicket.getTicket());
				ticket.setUpdateDate(new Date());
				ticket.setLoseEfficacyDate(new Date(new Date().getTime() + 7200*1000));
				updateAccessTokenService.updateTicket(ticket);
				System.out.println("-------------- 更新  js ticket 成功  --------------- ");
			}else{
				System.out.println("-------------- js ticket  没有过期  --------------- ");
			}
			result = JSONObject.fromObject(ticket).toString();
			out.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}
	/**
	 * 更新、获取js ticket
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/updateTicket.htm")
	public void updateJSTicket(HttpServletRequest request,HttpServletResponse response){
		AccessToken at = null;
		String  result = null;
		PrintWriter out = null;
		JsAPITicket ticket = null;
		try {
			ticket = updateAccessTokenService.queryTicket();
			out = response.getWriter();
			if(ticket == null ){
				at = updateAccessTokenService.queryToken();
				ticket = WechatJSTicketUtil.getJSTicket(at.getToken());
				updateAccessTokenService.addTicket(ticket);
				System.out.println("-------------- 新增  js ticket 成功  --------------- ");
			}else if(ticket != null){
				at = updateAccessTokenService.queryToken();
				JsAPITicket newTicket = WechatJSTicketUtil.getJSTicket(at.getToken());
				ticket.setTicket(newTicket.getTicket());
				ticket.setUpdateDate(new Date());
				ticket.setLoseEfficacyDate(new Date(new Date().getTime() + 7200*1000));
				updateAccessTokenService.updateTicket(ticket);
				System.out.println("-------------- 强制更新  js ticket 成功  --------------- ");
			}
			result = JSONObject.fromObject(ticket).toString();
			out.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}
	/**
	 * js-sdk 验证
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/signJsSDK.htm")
	public void signJsSDK(
			@RequestParam(value="url") String url,
			HttpServletRequest request,
			HttpServletResponse response){
		WxConfig wx = null;
		String  result = null;
		PrintWriter out = null;
		JsAPITicket ticket = null;
		try {
			out = response.getWriter();
			ticket = updateAccessTokenService.queryTicket();
			wx = WechatJSTicketUtil.getWXConfig(url, ticket.getTicket());
			result = JSONObject.fromObject(wx).toString();
			System.out.println("js-sdk参数:"+result);
			out.write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}
	
	/**
	 * 创建菜单
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/createMenu.htm")
	public void createWechaMenu(HttpServletRequest request,HttpServletResponse response){
		AccessToken at = null;
		JSONObject  result = null;
		PrintWriter out = null;
		Menu menu = WeixinUtil.initMenu();
		JSONObject smenu = JSONObject.fromObject(menu);
		try {
			at = updateAccessTokenService.queryToken();
			result = WeixinUtil.createMenu(at.getToken(), smenu.toString());
			out = response.getWriter();
			out.write(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.close();
		}
	}
}
